package com.elm.service.impl;

import com.elm.controller.DeliveryAddressController;
import com.elm.mapper.*;
import com.elm.po.*;
import com.elm.service.OrdersService;
import com.elm.service.UserService;
import com.elm.util.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class OrdersServiceImpl implements OrdersService {

    private final DeliveryAddressController deliveryAddressController;
	@Autowired
	private OrdersMapper ordersMapper;
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private BusinessMapper businessMapper;
	@Autowired
	private CartMapper cartMapper;
	@Autowired
	private DeliveryAddressMapper addressMapper;
	@Autowired
	private OrderDetailetMapper orderDetailetMapper;
    @Autowired
    private WalletMapper walletMapper;
	@Autowired
	private UserService userService;
	@Autowired
	private HttpServletRequest request;

    OrdersServiceImpl(DeliveryAddressController deliveryAddressController) {
        this.deliveryAddressController = deliveryAddressController;
    }

	private String getCurrentUserName() {
		String token = (String) request.getAttribute("token");
		return JwtUtil.getUsernameFromToken(token);
	}

	private String getCurrentUserType() {
		String token = (String) request.getAttribute("token");
		return JwtUtil.getUserTypeFromToken(token);
	}

	//需要传token，但无需身份验证
	@Transactional // 完整性保证
	@Override
	public Orders createOrders(Orders order) { 				//传token仅为获取信息
		User user = userMapper.getUserByName(getCurrentUserName());
        Business business = order.getBusiness();
		order.setCustomerId(user.getId());
		order.setBusinessId(business.getId());
		order.setAddressId(order.getDeliveryAddress().getId());
//		order.setOrderTotal(cartMapper.getTotalByUserIdByBusinessId(order.getCustomerId(), order.getBusinessId()));
		order.setOrderTotal(cartMapper.getTotalByUserIdByBusinessId(order.getCustomerId(), order.getBusinessId())+businessMapper.getBusinessById(order.getBusinessId()).getDeliveryPrice());
		int rows = ordersMapper.createOrders(order);
		if (rows <= 0) {
			throw new RuntimeException("添加订单失败");
		}
		// 对orderDetailet操作
		List<Cart> cartList = cartMapper.getCartByBusiness(order.getBusinessId(),user.getId() );
		List<OrderDetailet> orderDetailetList = new ArrayList<>();
		for (Cart c : cartList) {
			OrderDetailet od = new OrderDetailet();
			od.setOrder_id(order.getId());
			od.setFood_id(c.getFoodId());
			od.setQuantity(c.getQuantity());
			orderDetailetList.add(od);
		}
		orderDetailetMapper.saveOrderDetailetBatch(orderDetailetList);

		// 清空购物车,以一删多
		Cart cart = new Cart();
		cart.setBusinessId(order.getBusinessId());
		cart.setCustomerId(order.getCustomerId());
		cartMapper.removeCart(cart);

		// 直接通过自增ID查询刚刚插入的记录
		return ordersMapper.getOrdersById(order.getId());
	}



    @Override
    public Orders handleOrders(Integer orderId, String orderState,int paymentMethod) {
        //'订单状态：unpaid-未支付，paid-已支付，received-商家接单，delivering-配送中，ended-已结束，refunded-已退款，rejected-商家拒单',
        User user =userMapper.getUserByName(getCurrentUserName());
        Orders order =ordersMapper.getOrdersById(orderId);
        Business business = businessMapper.getBusinessById(order.getBusinessId());
        int businessId = order.getBusinessId();
//		if("USER".equals(getCurrentUserType()) && !userMapper.getStaffWorkByStaffId(user.getId()).contains(businessId))
//		{
//			throw new RuntimeException("权限不足：普通用户无权处理订单");          //这里的用户仅指USER，商家staff有权
//		}
        User boss = userMapper.getUserByName(getCurrentUserName());
        List<Business> businessList = businessMapper.getBusinessListByUserId(boss.getId());
        boolean isAssociated = businessList.stream()
                .anyMatch(biz -> biz.getId().equals(businessMapper.getBusinessById(businessId).getId()));
        if ("BUSINESS".equals(getCurrentUserType()) && !isAssociated) {
            throw new RuntimeException("错误：老板未关联此商家");
        }
        ordersMapper.handleOrders(orderId, orderState);

        //TODO:修改orders状态做出对应响应
        /*  1.未支付转已支付，为商家新增冻结余额
            2.已支付转已完成，将商家的冻结金额转为余额，更新用户消费金额和vip等级
           3.已支付转退款或已支付拒单，将商家的冻结金额减掉，将用户消费金额返还，更新用户消费金额和vip等级
        * */

        int userId = order.getCustomerId();
        int user_walletId =  walletMapper.getWalletIdByUserId(userId);
        System.out.println(userId);
        System.out.println(business.getUserId());
        int business_walletId = walletMapper.getWalletIdByUserId(business.getUserId());


        if(orderState.equals("paid")){
            //增加商家的冻结金额
            walletMapper.addFrozen_balance(business_walletId,order.getOrderTotal());
            //扣用户钱
            Wallet userWallet = walletMapper.getWalletByUserId(userId);
            Double balance = userWallet.getBalance();
            Double overdraft = userWallet.getOverdraft();
            Double amount=0.0;
            Double overdraft_amount=0.0;
            if(paymentMethod==1){
                if(balance>=order.getOrderTotal())
                    amount=order.getOrderTotal();
                else if(balance<order.getOrderTotal()) {
                    amount = balance;
                    overdraft_amount=order.getOrderTotal()-balance;
                }
            }
            else if(paymentMethod==2){
                overdraft_amount=order.getOrderTotal();
            }
            walletMapper.increaseBalance(userId,amount*(-1),overdraft_amount);
            //新增流水表
            walletMapper.insertTransaction(orderId,userId,business.getUserId(),amount,overdraft_amount,"pay","支付");
        }
        else if(orderState.equals("ended")){
            walletMapper.addFrozen_balance(business_walletId,order.getOrderTotal()*(-1));
            // 入账id，出账id，总额，余额支付的金额，透支金额，备注        由于这里只管商家的加钱，不需要在意用户是用什么支付的,透支就置为null了，意思是为商家加钱是通过order.getOrderTotal()加
            // 其实这里的出账id应该也用不上。。。
            walletMapper.recharge(business.getUserId(),order.getOrderTotal());
            //更新消费金额与vip
            walletMapper.addConsumption(user_walletId,order.getOrderTotal());
            double consumption=walletMapper.getWalletByUserId(userId).getConsumption();
            walletMapper.updateVip(user_walletId,checkVip(consumption));
        }
        else if(orderState.equals("refunded") || orderState.equals("rejected")){
            walletMapper.addFrozen_balance(business_walletId,order.getOrderTotal()*(-1));
            //获取流水表从而获取支付时，用户的组合支付情况，从而实现退款
            Transaction transaction =  walletMapper.getTransactionByOrder(orderId);
            double amount = transaction.getBalanceAmount();
            double overdraft_amount = transaction.getOverdraftAmount();
            //为用户加上原来的钱，余额和透支各加各的
            walletMapper.increaseBalance(userId,amount,overdraft_amount*(-1));
            //退款:更新流水表(订单号，入账，出账，总额，余额支付的金额，透支金额，备注)
            walletMapper.insertTransaction(orderId,business.getUserId(),userId,amount,overdraft_amount,"refund","退款");
//            //更新消费金额与vip  !!! 不需要了，退款仅发生在订单未完成的情况下
//            walletMapper.addConsumption(user_walletId,order.getOrderTotal()*(-1));
//            double consumption=walletMapper.getWalletByUserId(userId).getConsumption();
//            walletMapper.updateVip(user_walletId,checkVip(consumption));
        }

        return ordersMapper.getOrdersById(orderId);
    }

    public int checkVip(double consumption){
        int vip_level = 0;
        if(consumption<500) vip_level=0;
        else if(consumption>=500 && consumption<2000) vip_level=1;
        else if(consumption>=2000 && consumption<5000) vip_level=2;
        else if(consumption>=5000 && consumption<12000) vip_level=3;
        else if(consumption>=12000 && consumption<30000) vip_level=4;
        else if(consumption>=30000) vip_level=5;
        return vip_level;
    }

	@Override
	public Orders getOrdersById(Integer orderId) {
		User user =userMapper.getUserByName(getCurrentUserName());
		Orders orders =ordersMapper.getOrdersById(orderId);
		int businessId = orders.getBusinessId();
		if("USER".equals(getCurrentUserType()) && !userMapper.getStaffWorkByStaffId(user.getId()).contains(businessId) && orders.getCustomerId()!=user.getId())
		{
			throw new RuntimeException("权限不足：普通用户无权查看订单");          //这里的用户仅指USER，商家staff有权
		}
		User boss = userMapper.getUserByName(getCurrentUserName());
		List<Business> businessList = businessMapper.getBusinessListByUserId(boss.getId());
		boolean isAssociated = businessList.stream()
		        .anyMatch(biz -> biz.getId().equals(businessMapper.getBusinessById(businessId).getId()));
		if ("BUSINESS".equals(getCurrentUserType()) && !isAssociated) {
			throw new RuntimeException("错误：老板未关联此商家");
		}
		return ordersMapper.getOrdersById(orderId);
	}

	@Override
	public List<Orders> getOrdersByUserId(Integer userId) {
		int currentUserId = userMapper.getUserIdByName(getCurrentUserName());
		if(userId!=currentUserId && !"ADMIN".equals(getCurrentUserType())) {
			throw new RuntimeException("权限不足：无权限查看他人订单");
		}
		//getBusinessById(Integer businessId)
		List<Orders> ordersList = ordersMapper.getOrdersByUserId(currentUserId);
		for (Orders order : ordersList) {
			order.setBusiness(businessMapper.getBusinessById(order.getBusinessId()));
		}
		return ordersList;
	}

	@Override
	public Orders addComment(Orders order) {
		User user = userMapper.getUserByName(getCurrentUserName());
		if (ordersMapper.getOrdersById(order.getId()).getCustomerId()!=user.getId() && !"ADMIN".equals(getCurrentUserType())) {
			throw new RuntimeException("权限不足：仅本人可发表评价");
		}
		if ("banned".equals(user.getStatus())) {
			throw new RuntimeException("权限不足：被封禁用户无权发表评价");
		}
		ordersMapper.addComment(order);
		return ordersMapper.getOrdersById(order.getId());
	}

	@Override
	public List<Orders> getAllCommentsByBusinessId(Integer businessId) {
		return ordersMapper.getAllCommentsByBusinessId(businessId);
	}

	@Override
	public List<Orders> getAllComments() {
		if (!"ADMIN".equals(getCurrentUserType())) {
			throw new RuntimeException("权限不足：仅管理员有权查看");
		}
		return ordersMapper.getAllComments();
	}

	//本人以及ADMIN有权
	@Override
	public Integer reviewComment(Integer orderId,Integer result) {
		User user = userMapper.getUserByName(getCurrentUserName());
		if (!"ADMIN".equals(getCurrentUserType()) && ordersMapper.getOrdersById(orderId).getCustomerId()!=user.getId()) {
			throw new RuntimeException("权限不足：仅管理员和自己可删除评论");
		}
		if(result==0)
			return ordersMapper.deleteComment(orderId);
		else {
			return ordersMapper.reviewComment(orderId);
		}
	}

	//对应商铺的staff和boss，以及ADMIN有权
	@Override
	public List<Orders> getAllOrders(Integer businessId) {
		User user =userMapper.getUserByName(getCurrentUserName());
		if("USER".equals(getCurrentUserType()) && !userMapper.getStaffWorkByStaffId(user.getId()).contains(businessId))
		{
			throw new RuntimeException("权限不足：普通用户无权查看商家订单总览");          //这里的用户仅指USER，商家staff有权
		}
		User boss = userMapper.getUserByName(getCurrentUserName());
		List<Business> businessList = businessMapper.getBusinessListByUserId(boss.getId());
		boolean isAssociated = businessList.stream()
		        .anyMatch(biz -> biz.getId().equals(businessMapper.getBusinessById(businessId).getId()));
		if ("BUSINESS".equals(getCurrentUserType()) && !isAssociated) {
			throw new RuntimeException("错误：老板未关联此商家");
		}
		return ordersMapper.getAllOrders(businessId);
	}

	@Override
	public List<Orders> getAllPaidOrders(Integer businessId) {
		User user =userMapper.getUserByName(getCurrentUserName());
		if("USER".equals(getCurrentUserType()) && !userMapper.getStaffWorkByStaffId(user.getId()).contains(businessId))
		{
			throw new RuntimeException("权限不足：普通用户无权查看商家订单总览");          //这里的用户仅指USER，商家staff有权
		}
		User boss = userMapper.getUserByName(getCurrentUserName());
		List<Business> businessList = businessMapper.getBusinessListByUserId(boss.getId());
		boolean isAssociated = businessList.stream()
		        .anyMatch(biz -> biz.getId().equals(businessMapper.getBusinessById(businessId).getId()));
		if ("BUSINESS".equals(getCurrentUserType()) && !isAssociated) {
			throw new RuntimeException("错误：老板未关联此商家");
		}
		return ordersMapper.getAllPaidOrders(businessId);
	}

	@Override
	public List<Orders> getAllEndedOrders(Integer businessId) {
		User user =userMapper.getUserByName(getCurrentUserName());
		if("USER".equals(getCurrentUserType()) && !userMapper.getStaffWorkByStaffId(user.getId()).contains(businessId))
		{
			throw new RuntimeException("权限不足：普通用户无权查看商家订单总览");          //这里的用户仅指USER，商家staff有权
		}
		User boss = userMapper.getUserByName(getCurrentUserName());
		List<Business> businessList = businessMapper.getBusinessListByUserId(boss.getId());
		boolean isAssociated = businessList.stream()
		        .anyMatch(biz -> biz.getId().equals(businessMapper.getBusinessById(businessId).getId()));
		if ("BUSINESS".equals(getCurrentUserType()) && !isAssociated) {
			throw new RuntimeException("错误：老板未关联此商家");
		}
		return ordersMapper.getAllEndedOrders(businessId);
	}



//	//用户本人，商家staff和boss，ADMIN有权
//	@Override
//	public List<OrderDetailet> getDetailetsByOrder(Integer order) {
//		User user =userMapper.getUserByName(getCurrentUserName());
//		Orders orders =ordersMapper.getOrdersById(order);
//		int businessId = orders.getBusinessId();
//		if("USER".equals(getCurrentUserType()) && !userMapper.getStaffWorkByStaffId(user.getId()).contains(businessId) && orders.getCustomerId()!=user.getId())
//		{
//			throw new RuntimeException("普通用户无权查看订单详细");          //这里的用户仅指USER，商家staff有权
//		}
//		User boss = userMapper.getUserByName(getCurrentUserName());
//		List<Business> businessList = businessMapper.getBusinessListByUserId(boss.getId());
//		boolean isAssociated = businessList.stream()
//		        .anyMatch(biz -> biz.getId().equals(businessMapper.getBusinessById(businessId).getId()));
//		if ("BUSINESS".equals(getCurrentUserType()) && !isAssociated) {
//			throw new RuntimeException("错误：老板未关联此商家");
//		}
//		return orderDetailetMapper.getDetailetsByOrder(order);
//	}

}